<template>
  <div id="Stu">
    <div class="mt-4">
      <el-input
        v-model="queryValue"
        placeholder="请输入查询值"
        class="input-with-select"
        style="float: left;width: 300px"
        @keydown.enter.native="selectStu(selectValue, queryValue)"
      >
        <template #prepend>
          <el-select v-model="selectValue" placeholder="请选择查询项" style="width: 135px">
            <el-option label="姓名" value="sname" />
            <el-option label="性别" value="sex" />
            <el-option label="班级" value="classId" />
          </el-select>
        </template>
        <template #append>
          <el-button :icon="Search" :disabled="queryValue == null || selectValue == null" @click="selectStu(selectValue,queryValue)" />
        </template>
      </el-input>
      <el-button plain type="primary" circle style="margin-left: 20px" @click="clickAllStu" >All</el-button>
      <el-button plain :icon="Plus" :round="true" style="float: right" @click="clickToAdd">添加学生</el-button>
      <el-table :data="stuAllData" empty-text="未查询到数据！" table-layout="auto" >
        <el-table-column fixed prop="sname" label="姓名" />
        <el-table-column prop="sex" label="性别" >
          <template #default="scope">
            <el-tag
              :type="scope.row.sex === '男' ? '' : 'danger'"
              disable-transitions
            >
              {{ scope.row.sex }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sphone" label="手机号" />
        <el-table-column prop="classname" label="班级" />
        <el-table-column prop="tname" label="班导" />
        <el-table-column prop="remark" label="备注" min-width="500px" />
        <el-table-column fixed="right" label="操作" header-align="center" width="210">
          <template #default="scope">
            <el-button plain type="primary" :icon="Edit" @click="clickToModify(scope.row)">修改</el-button>
            <el-divider direction="vertical" />
            <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              icon-color="#626AEF"
              title="你确定要删除吗？"
              @confirm="clickToDelete(scope.row)"
            >
              <template #reference>
                <el-button type="danger" plain :icon="Delete">删除 </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        hide-on-single-page
        layout="prev, pager, next"
        :page-sizes="[10]"
        :total="total"
        :current-page="currentPage"
        @current-change="pageChange"
      />
    </div>
    <el-dialog
      v-model="stuDialogVisible"
      :title="stuTitle"
      width="30%"
      :before-close="closeForm"
    >
      <el-form
        ref="stuFormRef"
        :model="stuForm"
        :rules="stuRules"
        key="stuForm"
        label-width="100px"
        style="overflow: hidden;padding-right: 50px;width: 60%;margin: 10px auto"
      >
        <el-form-item label="姓名:" prop="sname" >
          <el-input v-model="stuForm.sname" placeholder="请输入姓名" clearable />
        </el-form-item>
        <el-form-item label="性别:" prop="sex">
          <el-radio-group v-model="stuForm.sex">
            <el-radio label="男" />
            <el-radio label="女" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号:" prop="sphone" >
          <el-input v-model="stuForm.sphone" placeholder="请输入手机号" clearable />
        </el-form-item>
        <el-form-item label="选择班级:" prop="classesId">
          <el-select v-model="stuForm.classesId" placeholder="请选择班级">
            <el-option v-for="cal in classAll" :key="cal" :label="cal.classname" :value="cal.classid" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注信息:" prop="remark">
          <el-input v-model="stuForm.remark" maxlength="50" resize="none" :rows="3" show-word-limit placeholder="请输入备注信息" type="textarea" />
        </el-form-item>
        <el-form-item style="float: right">
          <el-button-group>
            <el-button type="success" @click="submitForm(stuFormRef)">确认</el-button>
            <el-button type="info" @click="closeForm">取消</el-button>
          </el-button-group>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>

import {Plus,Edit,Delete,Search} from "@element-plus/icons-vue";
import { ElNotification } from 'element-plus'
import {ref,unref} from "vue";
import axios from "axios";

export default {
  name: "StuSys",
  setup() {

    /*表格*/
    let stuAllData = ref()
    let stuMode = ref(1)  // 1：全部，2：条件查询

    /*添加 and 修改*/
    const clickToAdd = () => {
      stuTitle.value = "添加学生"
      getClassName()
      stuDialogVisible.value = true
    }
    const clickToModify = (data) => {
      stuTitle.value = "修改学生信息"
      getClassName()
      stuDialogVisible.value = true
      stuForm.value = JSON.parse(JSON.stringify(data))
    }
    const clickToDelete = (data) => {
      axios.post("/api/deleteStu", data, {
        headers: {
          token: localStorage.getItem("token")
        }
      }).then(res=>{
        if (res.data.code === 200) {
          ElNotification({
            title: '成功',
            message: res.data.msg,
            type: 'success',
            offset: 100,
          })
        } else {
          ElNotification({
            title: '错误',
            message: res.data.msg,
            type: 'error',
            offset: 100,
          })
        }
        stuMode.value = 1
        currentPage.value = 1
        getStuAll("/api/stuAll?pageNum=1&pageSize=10")
      })
    }

    /*查询*/
    let queryValue = ref()
    let selectValue = ref()
    const clickAllStu = () => {
      stuMode.value = 1
      currentPage.value = 1
      queryValue.value = ""
      selectValue.value = ""
      getStuAll("/api/stuAll?pageNum=1&pageSize=10")
    }
    const selectStu = (s,q) => {
      if (s == null || q == null) {
        clickAllStu()
      } else {
        if (s === "sax") {
          if (q !== "男" && q !== "女") {
            ElNotification({
              title: '错误',
              message: '查询性别值只能为 男 or 女',
              type: 'error',
              offset: 100,
            })
            return;
          }
        }
        stuMode.value = 2
        currentPage.value = 1
        getStuAll("/api/stuByName?pageNum=1&pageSize=10&selectValue="+s+"&queryValue="+q)
      }
    }

    /*分页*/
    let total = ref(0)
    let currentPage = ref(1)
    const pageChange = (pageNum) => {
      if (stuMode.value === 1) {
        currentPage.value = pageNum
        getStuAll("/api/stuAll?pageNum="+pageNum+"&pageSize=10")
      } else if (stuMode.value === 2) {
        currentPage.value = pageNum
        getStuAll("/api/stuByName?pageNum="+pageNum+"&pageSize=10&selectValue="+selectValue.value+"&queryValue="+queryValue.value)
      }
    }

    /*弹出对话框*/
    let stuTitle = ref("添加学生")
    let stuDialogVisible = ref(false)
    let stuFormRef = ref()
    let stuForm = ref({
      sname: "",
      sex: "",
      sphone: "",
      classesId: "",
      remark: ""
    })
    let stuRules = ref()
    const classAll = ref()
    const submitForm = (formEl) => {
      if (!formEl) return
      formEl.validate((valid) => {
        if (valid) {
          if (stuTitle.value === "添加学生") {
            axios.post("/api/addStu", JSON.parse(JSON.stringify(stuForm.value)), {
              headers: {
                token: localStorage.getItem("token")
              }
            }).then(res=>{
              if (res.data.code === 200) {
                ElNotification({
                  title: '成功',
                  message: res.data.msg,
                  type: 'success',
                  offset: 100,
                })
              } else {
                ElNotification({
                  title: '错误',
                  message: res.data.msg,
                  type: 'error',
                  offset: 100,
                })
              }
              stuMode.value = 1
              currentPage.value = 1
              getStuAll("/api/stuAll?pageNum=1&pageSize=10")
            })
          } else if (stuTitle.value === "修改学生信息") {

            axios.post("/api/updateStu", JSON.parse(JSON.stringify(stuForm.value)),{
              headers: {
                token: localStorage.getItem("token")
              }
            }).then(res=>{
              if (res.data.code === 200) {
                ElNotification({
                  title: '成功',
                  message: res.data.msg,
                  type: 'success',
                  offset: 100,
                })
              } else {
                ElNotification({
                  title: '错误',
                  message: res.data.msg,
                  type: 'error',
                  offset: 100,
                })
              }
              stuMode.value = 1
              currentPage.value = 1
              getStuAll("/api/stuAll?pageNum=1&pageSize=10")
            })
          } else {
            console.log("error")
          }
          stuDialogVisible.value = false
          unref(stuFormRef).resetFields()
        } else {
          return false
        }
      })
    }
    const closeForm = () => {
      stuDialogVisible.value = false
      stuForm.value = {}
      unref(stuFormRef).resetFields()
      console.log(stuForm.value)
    }


    /*数据*/
    getStuAll("/api/stuAll?pageNum=1&pageSize=10")

    function getStuAll(url) {
      axios.get(url, {
        headers: {
          token: localStorage.getItem("token")
        }
      }).then((res => {
        if (res.data.code === 200) {
          stuAllData.value = res.data.data.studentAllList
          total.value = res.data.data.total
        } else {
          ElNotification({
            title: '错误',
            message: res.data.msg,
            type: 'error',
            offset: 100,
          })
          stuAllData.value = []
          total.value = 0
        }
      }))
    }
    const getClassName = () => {
      axios.get("/api/classNameAll").then(res=>{
        classAll.value = res.data.data
      })
    }
    stuRules.value = {
      sname: [
        { required: true, trigger: 'blur', validator: checkName },
      ],
      sex: [
        { required: true, trigger: 'blur', validator: checkSax }
      ],
      sphone: [
        { required: true, trigger: 'blur', validator: checkPhone }
      ],
      classesId: [
        { required: true, trigger: 'blur', validator: checkClass }
      ]
    }
    function checkName (rule, value, callback) {
      if (!value) {
        return callback(new Error('请输入姓名'));
      } else {
        callback()
      }
    }
    function checkSax (rule, value, callback) {
      if (!value) {
        return callback(new Error('请输入性别'));
      } else {
        callback()
      }
    }
    function checkPhone (rule, value, callback) {
      if (!value) {
        return callback(new Error('请输入手机号'));
      } else {
        callback()
      }
      setTimeout(() => {
        let myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
        if (!myreg.test(value)) {
          callback(new Error('请输入正确的手机号'));
        } else {
          callback();
        }
      }, 1000);
    }
    function checkClass (rule, value, callback) {
      if (!value) {
        return callback(new Error('请选择班级'));
      } else {
        callback()
      }
    }

    return {
      /*表格*/
      stuAllData,
      /*查询*/
      queryValue,
      selectStu,
      selectValue,
      clickAllStu,
      /*添加 and 修改*/
      clickToModify,
      clickToDelete,
      clickToAdd,
      /*分页*/
      total,
      pageChange,
      currentPage,
      /*弹出对话框*/
      stuTitle,
      stuDialogVisible,
      stuFormRef,
      stuForm,
      stuRules,
      classAll,
      submitForm,
      closeForm,
      /*图标*/
      Plus,
      Edit,
      Delete,
      Search
    }
  }
}
</script>

<style scoped>
#Stu {
  margin: 50px auto;
  width: 50%;
  min-width: 1000px;
}
.el-pagination {
  float: right;
  margin: 50px auto;
}
</style>